﻿'Proyecto de curso base de datos II
'Universidad Nacional de Ingeniería - Instituto de Estudios Superiories
'Copyright (c) 2008 - Adolfo Fitoria <adolfo.fitoria@gmail.com>
'Bajo licencia GNU Public Licence v.2
Imports System.Data
Imports System.Data.SqlClient
Imports System.Linq

Public Class MainForm
#Region "Atributos"
    Dim user As Usuario
    Dim modificar As Boolean = False
    Dim pacienteActual As Paciente = Nothing
    Dim con As Conexion
    Dim pacientes As New Collection
    Dim tabla As New DataTable("Resultados")
#End Region
    Public Sub New(ByVal user As Usuario)
        Me.user = user
        InitializeComponent()
        tabla.Columns.Add(New DataColumn("id"))
        tabla.Columns.Add(New DataColumn("Nombre Completo"))
        tabla.Columns.Add(New DataColumn("Telefono"))
        tabla.Columns.Add(New DataColumn("email"))
        Me.resultadosBusqueda.DataSource = tabla
        rellenarDataGrid()
    End Sub
#Region "CrearMod"
    Private Sub btnLimpiar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLimpiar.Click
        clearFields()
    End Sub

    Private Sub clearFields()
        txtBuscar.Text = Nothing
        txtEmail.Text = Nothing
        txtOcupacion.Text = Nothing
        txtPrimerApellido.Text = Nothing
        txtPrimerNombre.Text = Nothing
        txtSegundoApellido.Text = Nothing
        txtSegundoNombre.Text = Nothing
        txtTelefono.Text = Nothing
    End Sub

    Private Sub btnCreateMod_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateMod.Click
        'already improven :)

        If validar() Then
            If modificar = False Then
                Dim nuevoPaciente As New Paciente(txtPrimerNombre.Text, txtPrimerApellido.Text, _
                                                  txtSegundoNombre.Text, txtSegundoApellido.Text, _
                                                  txtTelefono.Text, txtEmail.Text, txtOcupacion.Text)

                TabControl.TabPages(0).Focus()
                clearFields()
            Else
                pacienteActual.modificar_paciente(txtPrimerNombre.Text, txtPrimerApellido.Text, _
                                                   txtSegundoNombre.Text, txtSegundoApellido.Text, _
                                                   txtTelefono.Text, txtEmail.Text, txtOcupacion.Text)
                
                TabControl.TabPages(0).Focus()
                clearFields()
            End If
        Else
            txtPrimerApellido.Focus()
        End If

    End Sub

    Private Sub cambioStatus()
        If modificar = True Then
            'If pacienteActual not nothing Then
            '    MsgBox("Paciente no seleccionado")
            'Else
            Me.txtPrimerApellido.Text = Me.pacienteActual.primerApellido
            Me.txtPrimerNombre.Text = Me.pacienteActual.PrimerNombre
            Me.txtSegundoNombre.Text = Me.pacienteActual.segundoNombre
            Me.txtSegundoApellido.Text = Me.pacienteActual.segundoApellido
            Me.txtTelefono.Text = Me.pacienteActual.telefono
            Me.txtEmail.Text = Me.pacienteActual.email
            Me.txtOcupacion.Text = Me.pacienteActual.ocupacion
            Me.tabAddModPaciente.Text = "Modificar Paciente"
            Me.btnCreateMod.Text = "Modificar Paciente"
            'End If
        Else
            Me.tabAddModPaciente.Text = "Agregar Paciente"
            Me.btnCreateMod.Text = "Agregar Paciente"
        End If
    End Sub

    Private Sub cargarPacientes()
        pacientes.Clear()
        con = New Conexion
        con.Conectar()
        Dim comando As New SqlCommand("cargar_pacientes", con.SqlCon)
        Dim dr As SqlDataReader
        dr = comando.ExecuteReader

        Dim pacient As Paciente
        'filling the pacientes collection with all pacientes.
        While dr.Read
            pacient = New Paciente(Int32.Parse(dr.Item(0).ToString))
            pacientes.Add(pacient)
        End While
        con.Desconectar()
    End Sub
#End Region
#Region "Busqueda"
    Private Sub BtnBuscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnBuscar.Click
        cargarPacientes()
        'TODO improve the query to search with regular expresions too.
        Dim palabras() As String
        palabras = txtBuscar.Text.Split(" ")
        Dim query = Nothing

        Select Case palabras.Length
            Case 0
                MsgBox("Introdusca un texto por favor", MsgBoxStyle.Critical, "Error")

            Case 1
                query = (From paciente As Paciente In pacientes _
                                         Where paciente.NombreCompleto Like txtBuscar.Text _
                                         Or paciente.PrimerNombre Like palabras(0) _
                                         Or paciente.primerApellido Like palabras(0) _
                                         Select paciente).Distinct

            Case Else
                query = (From paciente As Paciente In pacientes _
                            Where paciente.NombreCompleto Like txtBuscar.Text _
                            Or paciente.PrimerNombre Like palabras(0) _
                            Or paciente.primerApellido Like palabras(0) _
                            Or paciente.PrimerNombre Like palabras(1) _
                            Or paciente.primerApellido Like palabras(1) _
                            Select paciente).Distinct
        End Select

        Dim elemento As Paciente
        If Me.resultadosBusqueda.Rows.Count > 0 Then
            tabla.Rows.Clear()
            Me.resultadosBusqueda.Update()
        End If

        For Each elemento In query
            rellenarPacienteDataGrig(elemento)
        Next
    End Sub
#End Region

#Region "GUI"
    Private Sub SobreToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SobreToolStripMenuItem.Click
        Dim about As New about
        about.ShowDialog()
    End Sub

    Private Sub SalirToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SalirToolStripMenuItem.Click
        Application.Exit()
    End Sub

    Private Sub MainForm_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing 'imcompleto
        Dim result As MsgBoxResult
        result = MsgBox("Realmente desea salir?", MsgBoxStyle.YesNo)
        If result = MsgBoxResult.Yes Or result = MsgBoxResult.Ok Then
            Me.Dispose()
            Application.Exit()
        Else

        End If
    End Sub

    Private Sub MainForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Me.user.tipoDeUsuario = "admin" Then
            usersAdmin.Visible = True
        Else
            usersAdmin.Visible = False
        End If
        cargarPacientes()
        cambioStatus()
    End Sub

    Private Sub CerrarSesiónToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CerrarSesiónToolStripMenuItem.Click
        Me.user.logout()
        Dim login As New LoginFrom
        login.Show()
        Me.Close()
    End Sub

    Private Function validar() As Boolean
        If txtPrimerApellido.Text = "" Or txtPrimerNombre.Text = "" Then
            MsgBox("Error: El primer nombre y el primer apellido son necesarios.", MsgBoxStyle.Critical, "Error")
            Return False
        End If
        Return True
    End Function

    Private Sub EliminarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EliminarToolStripMenuItem.Click
        Dim idSeleccionado As Int32 = Me.resultadosBusqueda.SelectedRows(0).Cells(0).Value
        Dim pacienteSelec As New Paciente(idSeleccionado)
        Dim pregunta As MsgBoxResult
        pregunta = MsgBox("Desea Elimnar el paciente: " + vbNewLine + pacienteSelec.NombreCompleto, _
                          MsgBoxStyle.YesNo)
        If pregunta = MsgBoxResult.Ok Or pregunta = MsgBoxResult.Yes Then
            pacienteSelec.eliminar()
            Me.tabla.Rows.Clear()
        End If
    End Sub

    Private Sub resultadosBusqueda_CellContentDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles resultadosBusqueda.CellContentDoubleClick
        Dim pacienteSeleccionado As New Paciente( _
            Int32.Parse(Me.resultadosBusqueda.Rows(e.RowIndex).Cells("id").Value.ToString))
        MostrarCitas(pacienteSeleccionado)
    End Sub

    Private Sub ModifyToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ModifyToolStripMenuItem.Click
        Dim id As Int32 = Int32.Parse(Me.resultadosBusqueda.SelectedRows(0).Cells(0).Value.ToString)
        Me.pacienteActual = New Paciente( _
           Int32.Parse(id))
        Me.TabControl.SelectedTab = Me.tabAddModPaciente
        Me.modificar = True
        cambioStatus()
    End Sub

    Private Sub verCitasToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles verCitasToolStripMenuItem.Click
        Dim pacienteSeleccionado As New Paciente( _
                  Int32.Parse(Me.resultadosBusqueda.SelectedRows(0).Cells("id").Value.ToString))
        MostrarCitas(pacienteSeleccionado)
    End Sub

    Private Sub AgregarNuevoToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AgregarNuevoToolStripMenuItem.Click
        Me.modificar = False
        cambioStatus()
        Me.TabControl.SelectedTab = Me.tabAddModPaciente
        clearFields()
    End Sub
#End Region
    Private Sub rellenarPacienteDataGrig(ByVal paciente As Paciente)
        Dim fila As DataRow = tabla.NewRow
        fila.Item("id") = paciente.Id_cliente
        fila.Item("Nombre Completo") = paciente.NombreCompleto
        fila.Item("Telefono") = paciente.telefono
        fila.Item("email") = paciente.email
        tabla.Rows.Add(fila)
    End Sub

    Private Sub rellenarDataGrid()
        Dim i As Paciente
        For Each i In pacientes
            rellenarPacienteDataGrig(i)
        Next
    End Sub

    Public Sub MostrarCitas(ByVal paciente As Paciente)
        Dim citafrm As New citaForm(paciente)
        citafrm.Show(Me)
        Me.Enabled = False
    End Sub

    Private Sub usersAdmin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles usersAdmin.Click
        Dim formAdmin As New userAdmin
        Me.Enabled = False
        formAdmin.ShowDialog(Me)
    End Sub

End Class